package com.itheima.service;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//自定义类实现 UserDetailsService接口  并重写其方法
@Component
public class MyDetailService implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //模拟数据库
    private static Map<String, User> map=new HashMap<>();
    //初始化数据
    /*static {
        map.put("zs",new User("1","zs","123"));
        map.put("ls",new User("2","ls","123"));
    }*/

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initData();
        //如果传入username值等于zs
        if ("zs".equals(username)){
            User user=map.get(username);
            System.out.println(user);
            //获取用户名
            String name = user.getUsername();
            //获取密码
            String password = user.getPassword();
            //定义角色,权限集合
            List<GrantedAuthority> list=new ArrayList<>();
            //添加角色,权限
            list.add(new SimpleGrantedAuthority("ROLE_ADD"));
            list.add(new SimpleGrantedAuthority("ROLE_QUERY"));
            //返回User对象--构造器的三个参数为: 用户名 密码 角色权限的集合
            return new org.springframework.security.core.userdetails.User(username,password,list);
        }
        //如果传入username值等于zs
        if ("ls".equals(username)){
            User user=map.get(username);
            System.out.println(user);
            //获取用户名
            String name = user.getUsername();
            //获取密码
            String password = user.getPassword();
            //定义角色,权限集合
            List<GrantedAuthority> list=new ArrayList<>();
            //添加角色,权限
            list.add(new SimpleGrantedAuthority("ROLE_UPDATE"));
            list.add(new SimpleGrantedAuthority("ROLE_ADD"));
            //返回User对象--构造器的三个参数为: 用户名 密码 角色权限的集合
            return new org.springframework.security.core.userdetails.User(username,password,list);
        }
        //返回null,说明认证失败
        return null;

    }
    private void initData() {
        String encode = bCryptPasswordEncoder.encode("123");

        System.out.println(encode);
        map.put("zs",new User("1","zs",encode));
        map.put("ls",new User("2","ls",encode));
    }
}
